package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.XMLFormatter;

import static java.util.Arrays.sort;

/**
 * @Project : AlgorithmLearning
 * @Package : Leetcode
 * @File : Q0040.java
 * @Author : WangRuoyu
 * @Date 2023/11/1 20:23
 */


public class Q0040 {
    int[] candidates;
    int target;
    boolean[] st;
    List<Integer> tmp = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();

    private void dfs(int k, int sum) {
        if (sum == target) {
            res.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = k; i < candidates.length; i++) {
            if (candidates[i] > target - sum) return;
            if (i > 0 && candidates[i] == candidates[i - 1] && !st[i - 1]) continue;
            st[i] = true;
            tmp.add(candidates[i]);
            dfs(i + 1, sum + candidates[i]);
            st[i] = false;
            tmp.remove(tmp.size() - 1);
        }
    }

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        this.candidates = candidates;
        this.target = target;
        this.st = new boolean[candidates.length];
        dfs(0, 0);
        return res;
    }


    public static void main(String[] args) {
        Q0040 sl = new Q0040();
        int[] candidates = {10, 1, 2, 7, 6, 1, 5};
        int target = 8;
        System.out.println(sl.combinationSum2(candidates, target));
    }
}